#!/bin/bash
set -e

cd $(dirname $0)/..

source ./scripts/version

BASEDOCKERFILE=./scripts/installer/BaseDockerfile.${ARCH}
DOCKERFILE=./scripts/installer/Dockerfile.${ARCH}
ARTIFACTS=./dist/artifacts

# build kexec
pushd .
cd scripts/installer/kexec
dapper
popd


# TODO maybe extract the creation of the syslinux cfg files
DIST=$(pwd)/dist
echo "mkdir -p ${DIST}/boot/isolinux/"
mkdir -p ${DIST}/boot/isolinux/
cat scripts/isolinux.cfg | envsubst > ${DIST}/boot/isolinux/isolinux.cfg
cat scripts/isolinux_label.cfg | LABEL=${VERSION} envsubst > ${DIST}/boot/linux-current.cfg
#cat scripts/isolinux_label.cfg | LABEL=debug APPEND="rancher.debug=true" envsubst > ${DIST}/boot/linux-previous.cfg
if [ "$OS_AUTOFORMAT" = "true" ]; then
    APPEND_AUTOFORMAT="rancher.state.autoformat=[/dev/sda,/dev/vda] rancher.state.dev=LABEL=RANCHER_STATE rancher.state.wait=true"
    cat scripts/global.cfg | APPEND="$APPEND_AUTOFORMAT" envsubst > ${DIST}/boot/global.cfg
else
    cat scripts/global.cfg | envsubst > ${DIST}/boot/global.cfg
fi
cp scripts/rancher.png ${DIST}/boot/


mkdir -p ./scripts/installer/build/boot
cp ./bin/ros ./scripts/installer/build
trap "rm -rf ./scripts/installer/build" EXIT

# installer base image - can be included in iso
# TODO: fix the fullinstaller Dockerfile to use the ${VERSION}${SUFFIX}
docker build \
    -t ${OS_REPO}/os-installer \
    --build-arg VERSION=${VERSION} \
    --build-arg KERNEL_VERSION=${KERNEL_VERSION} \
    -f $BASEDOCKERFILE \
    ./scripts/installer
docker save -o ${ARTIFACTS}/installer.tar ${OS_REPO}/os-installer
cp $DOCKERFILE ${ARTIFACTS}/

cp ${ARTIFACTS}/${INITRD} ./scripts/installer/build/boot
cp ${ARTIFACTS}/vmlinuz-${KERNEL_VERSION} ./scripts/installer/build/boot
cp -r ${DIST}/boot/* ./scripts/installer/build/boot
cp $DOCKERFILE ./scripts/installer/build/Dockerfile
# Full installer image with initrd - used for pulling from network
docker build \
    -t ${OS_REPO}/os \
    ./scripts/installer/build
docker tag ${OS_REPO}/os ${OS_REPO}/os:${VERSION}${SUFFIX}

docker save -o ${ARTIFACTS}/fullinstaller.tar ${OS_REPO}/os:${VERSION}${SUFFIX}
echo ${OS_REPO}/os:${VERSION}${SUFFIX} >> dist/images
echo Built ${OS_REPO}/os:${VERSION}${SUFFIX}
